<!--
 * @Author: PC9527\Jack sophia2152@qq.com
 * @Date: 2023-08-07 15:16:55
 * @LastEditors: PC9527\Jack sophia2152@qq.com
 * @LastEditTime: 2023-08-08 09:28:11
 * @Description: 
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="50%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './menus.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';

  import { getMenusList, createMenus, updateMenus } from '/@/api/system/menus';
  import { useMessage } from '/@/hooks/web/useMessage';

  export default defineComponent({
    name: 'MenusDrawer',
    components: { BasicDrawer, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);

      const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
        labelWidth: 100,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: { lg: 12, md: 24 },
      });

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;

        if (unref(isUpdate)) {
          setFieldsValue({
            ...data.record,
          });
        }
        const treeData = await getMenusList();
        updateSchema({
          field: 'pid',
          componentProps: { treeData },
        });
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增菜单' : '编辑菜单'));

      async function handleSubmit() {
        try {
          const values = await validate();
          setDrawerProps({ confirmLoading: true });
          const { createMessage } = useMessage();
          if (unref(isUpdate)) {
            await updateMenus(values.id, values).then(() => {
              createMessage.success('编辑成功');
            });
          } else {
            await createMenus(values).then(() => {
              createMessage.success('添加成功');
            });
          }
          closeDrawer();
          emit('success');
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      return { registerDrawer, registerForm, getTitle, handleSubmit };
    },
  });
</script>
